﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EpcTagLibrary.Pat
{
    public class ASCIIPatternField : PatternField
    {
        private string m_PatComponent;

        public ASCIIPatternField(string patComponent, bool isGroupingPattern, int maxBits)
            : base(patComponent, isGroupingPattern, maxBits)
        {
            m_PatComponent = patComponent;
        }

        public override bool MatchField(EPC epc)
        {
            bool Result = false;

            if (IsWild)
            {
                Result = true;
            }
            else if (IsRange)
            {
                throw new PatternMatchException("ASCII patterns cannot hava a range");
            }
            else 
            {
                string StringValue;
                try
                {
                    StringValue = (string)Property.GetValue(epc,new object[0]);
                }
                catch (Exception e)
                {
                    throw new PatternMatchException("Matching Error.",e);
                }

                Result = StringValue.Equals(Exact) && (StringValue.Length == m_PatComponent.Length);
            }

            return Result;                
        }

        public override GroupField GroupField(EPC epc, GroupField parent)
        {
            GroupField Result= null;

            if (MatchField(epc))
            {
                if (IsGrouping)
                {
                    try
                    {
                        string val = (string)Property.GetValue(epc,new object[0]);
                    }
                    catch (Exception e)
                    {
                        throw new PatternMatchException("Grouping Error.",e);
                    }
                }
                else
                {
                    Result = parent.FindOrAddGroup(this, Component);
                }
            }

            return Result;
        }

        public override string ToString()
        {
            StringBuilder Result = new StringBuilder();

            Result.Append("ASCIIPatternField(");
            Result.Append(Component);
            Result.Append(")");
            if (!IsRange && !IsWild)
            {
                Result.Append("Extract:");
                Result.Append(m_PatComponent);
            }
            else
            {
                Result.Append("Any");
            }

            Result.Append("}");

            return Result.ToString();
        }
    }
}
